const fs = require('fs');
const path = require('path');

function checkDirectory(src, dst, callback, filter){
  fs.access(dst, fs.constants.F_OK, (err) => {
    if(err){
      fs.mkdirSync(dst, {
        recursive: true
      });
      callback(src,dst, filter);
    }else{
      callback(src,dst, filter);
    }
  });
}

function copy(src,dst, filter = []){
  const paths = fs.readdirSync(src); //同步读取当前目录
  paths.forEach((path) =>{
    const _src=src + '/' + path;
    const _dst=dst +'/' + path;
    fs.stat(_src,(err,stats) => { //stats 该对象 包含文件属性
      if(err)throw err;
      if(stats.isFile()){ // 如果是个文件则拷贝
        if(!filter || (filter && filter.find(item => _src.endsWith(item)))){
          let readable = fs.createReadStream(_src);//创建读取流
          let writable = fs.createWriteStream(_dst);//创建写入流
          readable.pipe(writable);
        }
      }else if(stats.isDirectory()){ //是目录则 递归
        checkDirectory(_src,_dst, copy, filter);
      }
    });
  });
}

function copyComponentsLess(){
  copy(path.join(__dirname, '../src/components'), path.join(__dirname, '../dist/components'), ['.less'])
}

function copyDeclareFile(){
  copy(path.join(__dirname, '../src/components'), path.join(__dirname, '../dist/components'), ['.d.ts'])
}

// 1， 复制组件样式
copyComponentsLess()
// 3， 复制.d.ts
copyDeclareFile()
